<?php

namespace app\api\model;

use app\admin\event\SystemLog;
use app\admin\model\Admin;
use think\db\Query;
use think\Model;
use think\Db;

class StorageModel extends Base
{

    protected static function init()
    {
        self::observe(SystemLog::class);
    }

    protected $table ='instock';
    protected $field = ['id', 'status', 'number', 'create_time', 'supplier', 'warehouse', 'maker', 'relation_number', 'type', 'des'];

    public function getTypeAttr($value)
    {
        //单据类型 1采购单 2生产入库单 3调拨单 4销售退货单  5配货退货单
        switch ($value) {
            case 1:
                return '采购单';
            case 2:
                return '生产入库单';
            case 3:
                return '调拨单';
            case 4:
                return '销售退货单';
           default:
                return '配货退货单';
        }
    }

    public function getStatusAttr($value)
    {
        //状态 1待入库 2部分入库  3已入库 4已撤销
        switch ($value) {
            case 1:
                return '待入库';
            case 2:
                return '部分入库';
            case 3:
                return '已入库';
            default:
                return '已撤销';
        }
    }

    // 定义全局的查询范围
    protected function base($query)
    {
        $c = Admin::find(\app\http\GetUid::getUId());
        // 门店负责人可查看自己门店的所有信息
        if ($c->level == 2) {
            $maker = Admin::where('store', $c->store)->where('level', 3)->column('id');
        } elseif ($c->level == 1) {
            $maker = Admin::column('id');
        } else {
            $maker = $c->id;
        }
        $query->whereIn('maker', $maker);
    }

    public function getCreateTimeAttr($value)
    {
        return date('Y-m-d',$value);
    }
    /**
     * 入库单  列表
     */
    public function getOutList($data, $field = "", $order = "id desc")
    {
        $where = [];
        if ($data['start'] == 1) {
            if (!empty($data['status'])) {
                $where[] = ['i.status','=',$data['status']];
            } else {
                $where[] = ['i.status','in',[1,2,4]];
            }
        } else if ($data['start'] == 2) {
            if (!empty($data['status'])) {
                $where[] = ['i.status','=',$data['status']];
            } else {
                $where[] = ['i.status','in',[3,4]];
            }
        }
        if($data['start_time'] && $data['end_time']){
            $where[] =['i.create_time','between',[$data['start_time'],$data['end_time']]];
        }
        if (!empty($data['supplier'])) {
            $where[] = ['i.supplier','=',$data['supplier']];
        }
        if (!empty($data['warehouse'])) {
            $where[] = ['i.warehouse','=',$data['warehouse']];
        }
        if (!empty($data['number'])) {
            $where[] = ['i.number','like', "%" . $data['number'] . "%"];
        }
        if (!empty($data['maker'])) {
            $where[] = ['i.maker','=',$data['maker']];
        }
        if (!empty($data['store'])) {
            $where[] = ['a.store','=',$data['store']];
        }
        $list =Db::name('instock')->alias('i')
            ->leftJoin('supplier s','s.id =i.supplier')
            ->leftJoin('warehouse w','w.id =i.warehouse')
            ->leftJoin('admin a','a.id =i.maker')
            ->field('i.*,s.name as supplier,w.name as warehouse,a.name as maker')
            ->where($where)->order('id desc')->page($data['page'],$data['size'])->paginate($data['size']);
        $list->each(function ($v) {
            $v['type_name'] = $this->getTypeAttr($v['type']);
            $v['create_time'] = $this->getCreateTimeAttr($v['create_time']);
            switch ($v['status']){
                case 1:
                    $v['status_name'] = "待入库";
                    $v['status2'] =32;
                    break;
                case 2:
                    $v['status_name'] = "部分入库";
                    $v['status2'] =33;
                    break;
                case 3:
                    $v['status_name'] = "已入库";
                    $v['status2'] =35;
                    break;
                default:
                    $v['status_name'] = "已撤销";
                    $v['status2'] =34;
                    $v['status3'] =36;
            }
            return $v;
        });
        return $list;
    }

    /**
     * 入库单  详情
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($id)
    {
        $list = $this->getOne($this->table,'*',['id'=>$id]);
        if($list['type'] ==1){//1采购单
            $current = $this->getOne('purchase','*',['id'=>$list['relation_id']]);
            $list['goods'] = $this->getselectList('purchaserelation','*',['pid'=>$current['id']]);
        }else if($list['type'] ==2){//2生产入库单
            $current = $this->getOne('production','*',['id'=>$list['relation_id']]);
            $list['goods'] = $this->getselectList('production_relation','*',['pid'=>$current['id']]);
        }else if($list['type'] ==3){//3调拨单
            $current = $this->getOne('allot','*',['id'=>$list['relation_id']]);
            $list['goods'] = $this->getselectList('allotrelation','*',['pid'=>$current['id']]);
        }else if($list['type'] ==4){//4销售退货单
            $current = $this->getOne('salereturn','*',['id'=>$list['relation_id']]);
            $list['goods'] = $this->getselectList('salereturnrelation','*',['pid'=>$current['id']]);
        }else{//5配货退货单
            $current = $this->getOne('preparereturn','*',['id'=>$list['relation_id']]);
            $list['goods'] = $this->getselectList('preparereturnrelation','*',['pid'=>$current['id']]);
        }
        foreach($list['goods'] as $k=>$v){
            $dan =$this->getOne('product','commodity_id,color,size',['id'=>$v['product_id']]);
            $goods =$this->getOne('commodity','name,item,retail_price,goods_code,unit',['id'=>$dan['commodity_id']]);
            $list['goods'][$k]['name'] =$goods['name'];
            $list['goods'][$k]['item'] =$goods['item'];
            $list['goods'][$k]['price'] =$goods['retail_price'];
            $list['goods'][$k]['goods_code'] =$goods['goods_code'];
            $list['goods'][$k]['color'] =$this->getValue('color3',['id'=>$dan['color']],'name');
            $list['goods'][$k]['size'] =$this->getValue('color3',['id'=>$dan['size']],'name');
            $list['goods'][$k]['unit'] =$this->getValue('color1',['id'=>$goods['unit']],'name');
        }
        $list['supplier_name'] = $this->getValue('supplier',['id'=>$list['supplier']],'name');
        $list['supplier_phone'] = $this->getValue('supplier',['id'=>$list['supplier']],'phone');
        $list['warehouse_name'] = $this->getValue('warehouse',['id'=>$list['warehouse']],'name');
        $user = $this->getOne('admin','name,phone',['id'=>$list['maker']]);
        $list['maker_name'] = $user['name'];
        $list['maker_phone'] = $user['phone'];
        $list['create_time'] = $this->getCreateTimeAttr($list['create_time']);
        return $list;
    }

    /**
     * 入库单  入库
     * @param $id
     * @param $option
     * @return int
     */
    public function getDepot($id,$option)
    {
        $list =$this->getOne($this->table,'*',['id'=>$id]);
        if($list['type'] ==1){//采购单
            $current = $this->getOne('purchase','*',['id'=>$list['relation_id']]);
            $list['goods'] = $this->getselectList('purchaserelation','*',['pid'=>$current['id']]);
            foreach($list['goods'] as $k=>$v){
                foreach($option as $k1=>$v1){
                    if($v['id'] == $v1['id']){
                        if(isset($v1['num'])){
                            $list['goods'][$k]['num'] =$v1['num'];
                        }else{
                            throw new \Exception('请输入有效数量');
                        }
                    }
                }
            }
            $arr =[];
            foreach($list['goods'] as $k=>$v){
                if(isset($v['num'])) {
                    $yu = $v['put_number'] - $v['number'];//剩余待入库数量
                    //输入的数量大于剩余待入库数量
                    if ($v['num'] > $yu) {
                        throw new \Exception('超出库存上限');
                    } else if ($v['num'] < $yu) {
                        //输入的数量小于剩余待入库数量 部分入库
                        $arr[] = 1;
                    }
                    $this->getSetInc('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'stock', $v['num']);
                    $this->getSetInc('purchaserelation', ['id' => $v['id']], 'number', $v['num']);
                    $this->getSetDec('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'put_in', $v['num']);
                    $stock = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'stock');
                    $flow = [
                        'goods_id' => $v['product_id'],
                        'create_time' => time(),
                        'warehouse' => $list['warehouse'],
                        'type' => '采购单',
                        'number' => $list['number'],
                        'add_num' => $v['num'],
                        'sur_num' => $stock + $v['num']
                    ];
                    $this->getAdd('flowing_water', $flow);
                }
            }
            $payment =[
                'customer_id' => $current['supplier'],
                'customer_type' => 'supplier',
                'maker' => $current['uid'],
                'set_account' => $current['set_account'],
                'account_type_id' => $current['type'],
                'out_amount' => $current['payment'],
                'des' => $current['des'],
                'create_time' => time(),
                'images' => $current['images'],
                'business_type' => '采购单',
                'business_number' => $current['number'],
                'business_time' => $current['create_time'],
            ];
            $this->getAdd('set_account_flow', $payment);
            $small = [
                'customer_id' => $current['supplier'],
                'customer_type' => 'supplier',
                'maker' => $current['uid'],
                'set_account' => $current['set_account'],
                'account_type_id' => 15,
                'out_amount' => $current['small'],
                'des' => $current['des'],
                'create_time' => time(),
                'images' => $current['images'],
                'business_type' => '采购单',
                'business_number' => $current['number'],
                'business_time' => $current['create_time'],
            ];
            $this->getAdd('set_account_flow', $small);
            $feiyong = [
                'customer_id' => $current['supplier'],
                'customer_type' => 'supplier',
                'maker' => $current['uid'],
                'set_account' => $current['set_account'],
                'account_type_id' => 15,
                'out_amount' => $current['money'],
                'des' => $current['des'],
                'create_time' => time(),
                'images' => $current['images'],
                'business_type' => '采购单',
                'business_number' => $current['number'],
                'business_time' => $current['create_time'],
            ];
            $this->getAdd('set_account_flow', $feiyong);
            if(count($arr) == count($list['goods']) || array_sum(array_unique($arr)) ==1){
                //部分入库
                $this->getSetField('purchase',['id'=>$current['id']],['status'=>2]);
                $this->getSetField('instock',['id'=>$id],['status'=>2]);
            }else{
                //全部入库
                $this->getSetField('purchase',['id'=>$current['id']],['status'=>4]);
                $this->getSetField('instock',['id'=>$id],['status'=>3]);
            }
        }else if($list['type'] ==2){//生产入库单
            $current = $this->getOne('production','*',['id'=>$list['relation_id']]);
            $list['goods'] = $this->getselectList('production_relation','*',['pid'=>$current['id']]);
            foreach($list['goods'] as $k=>$v){
                $this->getSetInc('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'stock', $v['put_number']);
                $this->getSetDec('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'put_in', $v['put_number']);
                $stock = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'stock');
                $flow =[
                    'goods_id' =>$v['product_id'],
                    'create_time' =>time(),
                    'warehouse' =>$list['warehouse'],
                    'type' =>'生产入库单',
                    'number' =>$list['number'],
                    'add_num' =>$v['put_number'],
                    'sur_num' =>$stock + $v['put_number']
                ];
                $this->getAdd('flowing_water',$flow);
            }
            //全部入库
            $this->getSetField('production',['id'=>$current['id']],['status'=>2]);
            $this->getSetField('instock',['id'=>$id],['status'=>3]);
        }
        return 1;
    }

    /**
     * 入库单 撤销
     * @param $id
     * @return int
     */
    public function getRevoke($id)
    {
        $list =$this->getOne($this->table,'*',['id'=>$id]);
        if($list['type'] ==1){//采购单
            $this->getSetField('purchase',['id'=>$list['relation_id']],['status'=>3]);
            $list['goods'] = $this->getselectList('purchaserelation','*',['pid'=>$list['relation_id']]);
            foreach($list['goods'] as $k=>$v){
                $this->getSetDec('product_stock',['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']],'stock',$v['number']);
            }
        }else if($list['type'] ==2){//生产入库单
            $this->getSetField('production',['id'=>$list['relation_id']],['status'=>3]);
            $list['goods'] = $this->getselectList('production_relation','*',['pid'=>$list['relation_id']]);
            foreach($list['goods'] as $k=>$v){
                $this->getSetDec('product_stock',['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']],'stock',$v['put_number']);
            }
        }else if($list['type'] ==3){//调拨单
            $this->getSetField('allot',['id'=>$list['relation_id']],['status'=>3]);
            $current =$this->getOne('allot','*',['id'=>$list['relation_id']]);
            $current['goods'] = $this->getselectList('allotrelation','*',['pid'=>$list['relation_id']]);
            foreach($current['goods'] as $k=>$v){
                $this->getSetDec('product_stock',['product_id' => $v['product_id'],'warehouse'=>$current['call_in']],'stock',$v['put_number']);
                $this->getSetInc('product_stock',['product_id' => $v['product_id'],'warehouse'=>$current['call_out']],'stock',$v['put_number']);
            }
        }else if($list['type'] ==4){//销售退货单
            $this->getSetField('salereturn',['id'=>$list['relation_id']],['status'=>2]);
            $list['goods'] = $this->getselectList('salereturnrelation','*',['pid'=>$list['relation_id']]);
            foreach($list['goods'] as $k=>$v){
                $this->getSetDec('product_stock',['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']],'stock',$v['put_number']);
            }
        }else{//配货退货单
            $this->getSetField('preparereturn',['id'=>$list['relation_id']],['status'=>2]);
            $list['goods'] = $this->getselectList('preparereturnrelation','*',['pid'=>$list['relation_id']]);
            foreach($list['goods'] as $k=>$v){
                $this->getSetDec('product_stock',['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']],'stock',$v['put_number']);
            }
        }
        return $this->getSetField($this->table,['id'=>$id],['status'=>4]);
    }
}
